import HttpRequest from "./http"
import { merge } from "lodash-es"
import { getToken } from "@/utils/auth"
import useUserStore from "@/stores/user"
import cache from "@/utils/cache"

const requestHooks = {
    requestInterceptorsHook(options, config) {
        const { urlPrefix, baseUrl, withToken, isAuth } = config
        options.header = options.header ?? {}
        if (urlPrefix) {
            options.url = `${urlPrefix}${options.url}`
        }
        if (baseUrl) {
            options.url = `${baseUrl}${options.url}`
        }
        if (withToken && !options.header.token) {
            options.header.token = getToken()
        }
        return options
    },
    async responseInterceptorsHook(response, config) {
        const { isTransformResponse, isReturnDefaultResponse, isAuth } = config

        if (isReturnDefaultResponse) {
            return response
        }
        if (!isTransformResponse) {
            return response.data
        }

        const { logout } = useUserStore()
        const { code, data, message, timestamp } = response.data
        cache.set("serverTime", timestamp)
        switch (code) {
            case 200:
                return data

            case -1:
                logout()
                if (isAuth && !getToken()) {
                    uni.navigateTo({
                        url: "/pages/index/index"
                    })
                }
                return Promise.reject(message)

            default:
                uni.$u.toast(message || response.data)
                return Promise.reject(message)
        }
    },
    async responseInterceptorsCatchHook(options, error) {
        if (options.method?.toUpperCase() == "POST") {
            uni.$u.toast("请求失败")
        }
        return Promise.reject(error)
    }
}

const defaultOptions = {
    requestOptions: {
        timeout: 10 * 1000
    },
    baseUrl: `${import.meta.env.VITE_APP_BASE_URL}`,
    isReturnDefaultResponse: false,
    isTransformResponse: true,
    urlPrefix: "",
    ignoreCancel: false,
    withToken: true,
    isAuth: false,
    retryCount: 2,
    retryTimeout: 1000,
    requestHooks: requestHooks
}

function createRequest(opt) {
    return new HttpRequest(merge(defaultOptions, opt || {}))
}
const request = createRequest()
export default request
